package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.MarketStorageService;
import com.cskaoyan.market.service.impl.MarketStorageServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * ClassName: AdminStorageController
 * Package: com.cskaoyan.market.controller
 * Date: 2023/5/8 - 16:18
 * Description:
 */
@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageController extends HttpServlet {
    MarketStorageService marketStorageService = new MarketStorageServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/admin/storage/", "");
        switch (replace) {
            case "list":
                list(req, resp);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/admin/storage/", "");
        switch (replace) {
            case "update":
                update(req, resp);
                break;
            case "delete":
                delete(req, resp);
                break;
            case "create":
                create(req,resp);
                break;
        }
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part file = req.getPart("file");
        String contentType = file.getContentType();
        String name = file.getSubmittedFileName();
        long size = file.getSize();
        String substring = name.substring(name.indexOf("."));
        String key = UUID.randomUUID().toString();
        //改名
        key = key + substring;

        String upload = (String)getServletContext().getAttribute("upload");
        String domain = (String)getServletContext().getAttribute("domain");

        String absolutePath = upload+key;
        File filePath = new File(absolutePath);
        if(!filePath.getParentFile().exists()){
            //如果父级目录不存在，则我们创建所有的父级目录
            filePath.getParentFile().mkdirs();
        }
        file.write(filePath.getAbsolutePath());

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(name);
        marketStorage.setType(contentType);
        marketStorage.setSize((int)size);
        marketStorage.setUrl("/wx/storage/fetch/"+key);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorageService.addStorage(marketStorage);
        marketStorage.setUrl(domain + marketStorage.getUrl());
        String s = JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketStorage));
        resp.getWriter().println(s);
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String userName = req.getParameter("username");
        String key = req.getParameter("key");
        if (StringUtils.isEmpty(page) || StringUtils.isEmpty(limit)) {
            Object o = ResponseUtil.badArgument();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        if (StringUtils.isEmpty(sort)) {
            sort = "id";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }
        if (!("asc".equals(order) || "desc".equals(order))) {
            Object o = ResponseUtil.badArgumentValue();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        List<MarketStorage> marketStorages = marketStorageService.list(page, limit, sort, order, userName, key);

        if (marketStorages == null) {
            Object serious = ResponseUtil.serious();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(serious));
            return;
        }
        Object okList = ResponseUtil.okList(marketStorages);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(okList));
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = getRequestBody(req);
        MarketStorage marketStorage = JacksonUtil.getObjectMapper().readValue(requestBody, MarketStorage.class);
        if (StringUtils.isEmpty(marketStorage.getName()) || StringUtils.isEmpty(marketStorage.getKey()) || marketStorage.getId() == 0 || marketStorage.getSize() == 0 || StringUtils.isEmpty(marketStorage.getType())) {
            Object o = ResponseUtil.badArgument();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        marketStorageService.delet(marketStorage);
        Object ok = ResponseUtil.ok();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = getRequestBody(req);
        MarketStorage marketStorage = null;
        marketStorage = JacksonUtil.getObjectMapper().readValue(requestBody, MarketStorage.class);
        System.out.println(marketStorage);
        if (StringUtils.isEmpty(marketStorage.getName()) || StringUtils.isEmpty(marketStorage.getKey()) || marketStorage.getId() == 0 || marketStorage.getSize() == 0 || StringUtils.isEmpty(marketStorage.getType())) {
            Object o = ResponseUtil.badArgument();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        List<MarketStorage> marketStorages = marketStorageService.updte(marketStorage);
        if (marketStorages == null) {
            Object o = ResponseUtil.updatedDataFailed();
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        Object ok = ResponseUtil.ok(marketStorages);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    private static String getRequestBody(HttpServletRequest req) throws IOException {
        ServletInputStream in = req.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int length = 0;
        byte[] bytes = new byte[1024];
        while ((length = in.read(bytes)) != -1) {
            out.write(bytes, 0, length);
        }
        String requestBody = out.toString("utf-8");
        return requestBody;
    }
}
